package com.sfzd5.exam;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.google.gson.Gson;
import com.sfzd5.exam.helplibrary.exam.ExamInof;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StartActivity extends AppCompatActivity {
    final static int LoginRequestCode = 110;
    LinearLayout bt_start;
    LinearLayout bt_log;
    EditText et_ip;
    PApplication app;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        app = (PApplication) getApplication();

        //添加Timber来记录崩溃信息

        et_ip = findViewById(R.id.et_ip);
        SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
        if(sharedPreferences.contains("wsip")){
            String ip = sharedPreferences.getString("wsip", "");
            et_ip.setText(ip);
        }


        bt_log = findViewById(R.id.bt_log);
        bt_log.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(StartActivity.this, ShowLogActivity.class);
                startActivity(i);
            }
        });

        //ws://345.657.234:9002
        bt_start = findViewById(R.id.bt_start);
        bt_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String ip = et_ip.getText().toString().trim();
                if(isIP(ip)){
                    app.wsClient = new WsClient("ws://" + ip + ":9002");
                    app.wsClient.wsOpenListener = new WSOpenListener() {
                        @Override
                        public void onWSOpen(boolean sucess) {
                            if(sucess) {
                                app.wsClient.wsOpenListener = null;
                            } else {
                                Toast.makeText(StartActivity.this, "连接出错", Toast.LENGTH_SHORT).show();
                            }
                        }
                    };
                    app.wsClient.wsMessageListener = new WSMessageListener() {
                        @Override
                        public void onWSMessage(String msg) {
                            SharedPreferences sharedPreferences = getSharedPreferences("MyPreferences", MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            editor.putString("wsip", et_ip.getText().toString());
                            editor.commit();

                            app.setNewExamInfo(new Gson().fromJson(msg, ExamInof.class));

                            Intent i = new Intent(StartActivity.this, CameraActivity.class);
                            startActivity(i);
                        }
                    };
                    app.wsClient.start();
                } else {
                    Toast.makeText(StartActivity.this, "IP地址不对", Toast.LENGTH_SHORT).show();
                }
            }
        });

        bt_start.setEnabled(true);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    void Request() {
        //获取相机拍摄读写权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            //版本判断
            if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.CAMERA}, 1);
            }
        }
    }

    public boolean isIP(String addr)
    {
        if(addr.length() < 7 || addr.length() > 15 || "".equals(addr))
        {
            return false;
        }
        /**
         * 判断IP格式和范围
         */
        String rexp = "([1-9]|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}";
        Pattern pat = Pattern.compile(rexp);
        Matcher mat = pat.matcher(addr);
        boolean ipAddress = mat.find();
        //============对之前的ip判断的bug在进行判断
        if (ipAddress==true){
            String ips[] = addr.split("\\.");
            if(ips.length==4){
                try{
                    for(String ip : ips){
                        if(Integer.parseInt(ip)<0||Integer.parseInt(ip)>255){
                            return false;
                        }
                    }
                }catch (Exception e){
                    return false;
                }
                return true;
            }else{
                return false;
            }
        }
        return ipAddress;
    }
}

